package com.gm.wholesale.module.order.ui

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.gm.commonlib.base.baseBean.BaseFragmentInfo
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment
import com.gm.commonlib.base.baseui.baseListviewUI.BaseListFragment
import com.gm.commonlib.module.evenbus.EventMessage
import com.gm.commonlib.util.timeUtils.DateTimeUtils
import com.gm.commonlib.views.timePickerView.TimePickerViewUtils
import com.gm.wholesale.R
import com.gm.wholesale.module.config.ConfigData
import com.gm.wholesale.module.evenbus.EventBusType
import com.gm.wholesale.module.order.adapter.ViewPagerAdapter
import com.gm.wholesale.module.order.bean.OrderBean
import com.gm.wholesale.module.order.bean.needorder.NeedOrderBean
import com.gm.wholesale.module.order.interfaces.ISearchOrderByTime
import com.gm.wholesale.module.order.listener.MyOnPageChangeListener
import com.gm.wholesale.module.order.listener.MyOnTabSelectedListener
import com.gm.wholesale.module.order.ui.needOrder.NeedOrderListFragment
import com.gm.wholesale.module.order.view.orderManger.NeedOrderDetailView
import com.gm.wholesale.module.order.view.orderManger.OrderDetailView
import com.gm.wholesale.util.ViewUtil
import com.gm.wholesale.view.tabview.TabView
import com.google.android.material.tabs.TabLayout

class OrderMangerFragment : BaseFragment() {
    private var orderListFragment: OrderListFragment? = null
    private var needOrderFragment: NeedOrderListFragment? = null
    private var mOrderDetailView: OrderDetailView? = null
    private var mNeedOrderDetailView: NeedOrderDetailView? = null
    private var mTabLayout: TabLayout? = null
    private var mViewPager: ViewPager? = null
    var choiceTimeTv: TextView? = null
    private var orderDetailLin: LinearLayout? = null
    var mAdapter: ViewPagerAdapter? = null
    private var mOrderingTimeBegin: String? = null
    private var mOrderingTimeEnd: String? = null
    private var mViewPagerAdapter: ViewPagerAdapter? = null
    var mCurrentTabPos = 0
    private var OrderTabView: TabView? = null
    private var needOrderTabView: TabView? = null
    private fun resetData() {
        mOrderingTimeBegin = null
        mCurrentTabPos = 0
    }

    override fun onCreateContentBody(parent: ViewGroup) {
        val view = LayoutInflater.from(context).inflate(R.layout.fragment_order_manger, parent)
        initView(view)
    }

    private fun initView(view: View) {
        mTabLayout = view.findViewById(R.id.tabLayout)
        mViewPager = view.findViewById(R.id.viewPager)
        orderDetailLin = view.findViewById(R.id.orderDetailLin)
        mTabLayout?.setupWithViewPager(mViewPager)
        mAdapter = adapter
        //给ViewPager设置适配器
        mViewPager?.adapter = mAdapter
        mViewPager?.isEnabled = false
        mViewPager?.offscreenPageLimit = 10
        //将TabLayout和ViewPager关联起来
        mTabLayout?.setupWithViewPager(mViewPager)

        //添加tab 自定义view
        val tab = mTabLayout?.getTabAt(0)
        OrderTabView = TabView(activity)
        tab!!.customView = OrderTabView
        OrderTabView!!.showView(ViewUtil.getString(activity, R.string.tab_order_title))
        OrderTabView!!.showCheck()
        if (ConfigData.getConfigData().hasNeedOrderPermission()) {
            val tab2 = mTabLayout?.getTabAt(1)
            needOrderTabView = TabView(activity)
            needOrderTabView?.showView(ViewUtil.getString(activity, R.string.tab_need_order_title))
            tab2!!.customView = needOrderTabView
            mTabLayout?.addOnTabSelectedListener(object : MyOnTabSelectedListener() {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    (tab.customView as TabView?)!!.showCheck()
                    mViewPager?.currentItem = tab.position
                }

                override fun onTabUnselected(tab: TabLayout.Tab) {
                    (tab.customView as TabView?)!!.showUnCheck()
                }
            })
            mViewPager?.addOnPageChangeListener(object : MyOnPageChangeListener() {
                override fun onPageSelected(position: Int) {
                    mCurrentTabPos = position
                    initTime()
                    if (needOrderFragment != null) {
                        needOrderFragment!!.getUnReviceOrderSize()
                    }
                    if (position == 1) { //需求单
                        hidOrderDetailView()
                        needOrderFragment!!.updateView()
                    } else {
                        hidNeedOrderDetailView()
                        orderListFragment!!.updateView()
                    }
                }
            })
        } else {
            mTabLayout?.visibility = View.GONE
        }
        initSearchView(view)
    }

    private fun initOrderDetail() {
        mOrderDetailView = OrderDetailView(activity)
        //把view添加进去
        orderDetailLin!!.addView(mOrderDetailView)
    }

    private fun initNeedOrderDetail() {
        mNeedOrderDetailView = NeedOrderDetailView(activity)
        mNeedOrderDetailView?.setOrderMangerFragment(this)
        orderDetailLin?.addView(mNeedOrderDetailView)
    }

    private fun initTime() {
        mOrderingTimeBegin = null
        val time = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.HMD2)
        choiceTimeTv?.text = "$time(今天)"
    }

    private fun initSearchView(view: View) {
        choiceTimeTv = view.findViewById(R.id.choiceTimeTv)
        initTime()
        choiceTimeTv?.setOnClickListener(View.OnClickListener {
            var nowTime = System.currentTimeMillis()
            if (!TextUtils.isEmpty(mOrderingTimeBegin)) {
                nowTime = DateTimeUtils.getTimeStringToLong(
                    mOrderingTimeBegin,
                    DateTimeUtils.LONG_DATETIME_FORMAT_STRING
                )
            }
            TimePickerViewUtils.showTimeByYMD(context, "选择时间", nowTime) { date, v ->
                mOrderingTimeBegin =
                    DateTimeUtils.formatDateTime(date, DateTimeUtils.SHORT_DATETIME_FORMAT_STRING)
                mOrderingTimeEnd = "$mOrderingTimeBegin 23:59:59"
                mOrderingTimeBegin = "$mOrderingTimeBegin 00:00:00"
                var time = DateTimeUtils.formatDateTime(date, DateTimeUtils.HMD2)
                if (DateTimeUtils.isToday(date)) {
                    time = "$time(今天)"
                }
                choiceTimeTv?.text = time
                updateViewByTime(mOrderingTimeBegin, mOrderingTimeEnd)
            }
        })
    }

    //todo 根据时间查询订单
    private fun updateViewByTime(begTime: String?, endTime: String?) {
        val iSearchOrderByTime = currentFragment as ISearchOrderByTime?
        iSearchOrderByTime!!.searchOrderByTime(begTime, endTime)
    }

    private val currentFragment: BaseListFragment<*, *>?
        get() = if (mCurrentTabPos == 0) {
            orderListFragment
        } else needOrderFragment

    override fun onReceiveEvent(event: EventMessage<*>) {
        super.onReceiveEvent(event)
        val type = event.code
        //显示现场单子详情
        if (type == EventBusType.UPDATE_ORDER_DETAIL.type) {
            showOrderView(event.data as OrderBean)
        } else if (type == EventBusType.SHOW_NEED_ORDER_DETAIL.type) {
            showNeedOrderView(event.data as NeedOrderBean)
        } else if (type == EventBusType.UPDATE_NEED_ORDER_DETAIL.type) {
            showNeedOrderView(event.data as NeedOrderBean)
        } else if (type == EventBusType.IS_PRINT.type) {
            if (mNeedOrderDetailView == null) return
            mNeedOrderDetailView!!.updateOrderState()
        }
    }

    fun hidOrderDetailView() {
        if (mOrderDetailView != null) {
            mOrderDetailView!!.visibility = View.GONE
        }
    }

    fun hidNeedOrderDetailView() {
        if (mNeedOrderDetailView == null) return
        mNeedOrderDetailView!!.visibility = View.GONE
    }

    fun hasNotOrderData() {
        hidOrderDetailView()
        hidNeedOrderDetailView()
    }

    fun showRedUnReviceOrderSize(size: Long) {
        needOrderTabView!!.showNt(size)
    }

    //现场订单
    private fun showOrderView(orderBean: OrderBean?) {
        hidNeedOrderDetailView()
        if (mOrderDetailView == null) {
            initOrderDetail()
        }
        if (mOrderDetailView != null) {
            mOrderDetailView!!.showOrderDetail(orderBean)
        }
    }

    //需求单子
    private fun showNeedOrderView(needOrderBean: NeedOrderBean?) {
        hidOrderDetailView()
        if (mNeedOrderDetailView == null) {
            initNeedOrderDetail()
        }
        if (mNeedOrderDetailView != null) {
            mNeedOrderDetailView!!.showView(needOrderBean)
        }
    }

    private val adapter: ViewPagerAdapter
        get() {
            val datas: MutableList<BaseFragmentInfo> = ArrayList()
            //订单列表
            orderListFragment = OrderListFragment()
            orderListFragment!!.setIsGetData(true)
            datas.add(BaseFragmentInfo(1, "订单", orderListFragment))
            if (ConfigData.getConfigData().hasNeedOrderPermission()) {
                //需求单列表
                needOrderFragment = NeedOrderListFragment()
                //获取未截单数量
                needOrderFragment!!.getUnReviceOrderSize()
                needOrderFragment!!.setOrderMangerFragment(this)
                needOrderFragment!!.setIsGetData(false)
                datas.add(BaseFragmentInfo(2, "需求单", needOrderFragment))
            }
            mViewPagerAdapter = ViewPagerAdapter(
                childFragmentManager, datas
            )
            return mViewPagerAdapter!!
        }

    private fun removeFragment() {
        if (orderListFragment != null) {
            removeFragment(orderListFragment!!)
            orderListFragment = null
        }
        if (needOrderFragment != null) {
            removeFragment(needOrderFragment!!)
            needOrderFragment = null
        }
    }

    private fun removeFragment(fragment: Fragment) {
        childFragmentManager.beginTransaction().remove(fragment).commitAllowingStateLoss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //todo 必须销毁它嵌套的相关fragment，不然下次添加会报错
        // todo因为子fragment没有销毁，还依附在当前fragment，不能再次被添加
        removeFragment() //移除嵌套的fragment
        resetData()
        if (mNeedOrderDetailView != null) {
            mNeedOrderDetailView!!.destory()
        }
        mOrderDetailView = null
        mNeedOrderDetailView = null
    }
}